<script setup>
import { updateAvatarAsync } from '@/api/user'

const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})
const emit = defineEmits(['update:modelValue'])

const imageUrl = ref(props.modelValue)
//头像上传
const uploadFile = async (param) => {
  let formData = new FormData()
  formData.append('img', param.file)
  const res = await updateAvatarAsync(formData)
  if (res && res.code + '' === '200') {
    ElMessage.success('成功更换头像！')
    imageUrl.value = res.data
    emit('update:modelValue', res.data)
  }

}

//上传前校验
const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    ElMessage.error('上传图片格式限制为JPG、PNG')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过2MB!')
    return false
  }
  return true
}

watch(() => props.modelValue, (val) => {
  imageUrl.value = val
}, {
  immediate: true
})

</script>


<template>
  <div>
    <el-upload ac class="avatar-uploader" :show-file-list="false" :before-upload="beforeAvatarUpload"
      :http-request="uploadFile">
      <el-avatar v-if="imageUrl" :size="50" :src="imageUrl" />
      <el-icon v-else class="avatar-uploader-icon">
        <Plus />
      </el-icon>
    </el-upload>
  </div>
</template>



<style lang="scss" scoped>
:deep(.avatar-uploader-icon) {
  width: 40px;
  height: 40px;
  padding: 10px;
  border: 1px dashed #3e3e3e;
  border-radius: 50%;
  transition: all 0.3s ease-in-out;

  &:hover {
    transform: rotate(90deg);
    border-color: #fd9d9d;
    color: #fd9d9d;
  }
}
</style>